package com.css.project.oa.travel.controller;

import com.css.common.utils.ConvertNumberToUpperUtils;
import com.css.common.utils.DateUtils;
import com.css.common.utils.file.FileUtils;
import com.css.framework.aspectj.lang.annotation.Log;
import com.css.framework.aspectj.lang.enums.BusinessType;
import com.css.framework.config.RuoYiConfig;
import com.css.framework.interceptor.annotation.RepeatSubmit;
import com.css.framework.web.controller.BaseController;
import com.css.framework.web.domain.AjaxResult;
import com.css.framework.web.page.TableDataInfo;
import com.css.project.oa.cash.domain.ProCash;
import com.css.project.oa.cash.domain.ProCashItem;
import com.css.project.oa.travel.domain.Travel;
import com.css.project.oa.travel.domain.TravelPrint;
import com.css.project.oa.travel.service.ITravelService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import static org.springframework.util.StreamUtils.BUFFER_SIZE;

@Api(value = "/travel ",description ="差旅报销单管理")
@RestController
@RequestMapping(value = "/travel")
public class TravelController extends BaseController {

    Logger log = LoggerFactory.getLogger(TravelController.class);
//    private static final Logger log = LoggerFactory.getLogger(HttpUtils.class);

    @Autowired
    public ITravelService travelService;

    /**
        * @Author 杜梦凯
        * @Description  获取列表
        * @Date 15:25 20-05-09,0009
        * @Param [proCash]
        * @return com.css.framework.web.page.TableDataInfo
    **/
    @ApiOperation("获取差旅报销单列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "expenseName", value = "报销人姓名", paramType="query", required = false),
            @ApiImplicitParam(name = "cashTimeStart", value = "费用报销日期   ", paramType="query", required = false)
    })
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public TableDataInfo list(@ApiIgnore Travel travel){
        startPage();
        List<Travel> list = travelService.getTravelList(travel);
        return getDataTable(list);
    }

    /**
        * @Author 杜梦凯
        * @Description  新增差旅报销单
        * @Date 16:27 20-05-12,0012
        * @Param [proCash, map]
        * @return com.css.framework.web.domain.AjaxResult
    **/
    @Log(title = "差旅报销单管理", businessType = BusinessType.INSERT)
    @ApiOperation("差旅报销单新增")
    @PostMapping(value = "/addTravel")
    @RepeatSubmit
    public AjaxResult addTravel(@RequestBody Travel travel, @RequestBody Map<String, Object> map) {
        travelService.add(travel, map.get("itemDataStr").toString(), map.get("itemData1Str").toString());
        return AjaxResult.success();
    }

    /**
     * @Author 杜梦凯
     * @Description  编辑差旅报销单
     * @Date 16:27 20-05-12,0012
     * @Param [proCash, map]
     * @return com.css.framework.web.domain.AjaxResult
     **/
    @Log(title = "差旅报销单管理", businessType = BusinessType.UPDATE)
    @ApiOperation("差旅报销单新增")
    @PostMapping(value = "/updateTravel")
    @RepeatSubmit
    public AjaxResult updateTravel(@RequestBody Travel travel, @RequestBody Map<String, Object> map) {
        travelService.update(travel, map.get("itemDataStr").toString(), map.get("itemData1Str").toString());
        return AjaxResult.success();
    }

    /**
     * @Author dumk
     * @Description  根据报销单id获取详情
     * @Date 16:33 20-05-12,0012
     * @Param [cashId]
     * @return com.css.framework.web.domain.AjaxResult
     **/
    @GetMapping(value= "/getTravelById")
    @ApiOperation("根据主键获取报销单详情")
    public AjaxResult getTravelById(Long travelId){
        Map<String, Object> map = travelService.getTravelById(travelId);
        return AjaxResult.success(map);
    }

    /**
     * @Author dumk
     * @Description  报销单删除
     * @Date 14:08 20-05-18,0018
     * @Param [travelIds]
     * @return com.css.framework.web.domain.AjaxResult
     **/
    @PreAuthorize("@ss.hasPermi('pro:travel:delete')")
    @Log(title = "报销单管理", businessType = BusinessType.DELETE)
    @RequestMapping(value = "/deleteTravel/{travelIds}")
    public AjaxResult deleteTravel(@PathVariable Long[] travelIds){
        return toAjax(travelService.deleteTravel(travelIds));
    }
    /**
     * 
    * @Title: getPrintMainInfo 
    * @Description: 获取打印主信息
    * @param @param travelId
    * @param @return    设定文件 
    * @author ShiChao 
    * @return AjaxResult    返回类型 
    * @throws
     */
    @GetMapping(value = "/getPrintMainInfo/{travelId}")
    public AjaxResult getPrintMainInfo(@PathVariable("travelId") Long travelId)
    {
        return AjaxResult.success(travelService.getMainTravelPrint(travelId));
    }
    /**
     * 
    * @Title: getTravelPrintList 
    * @Description: 获取报销单列表信息
    * @param @param travelId
    * @param @return    设定文件 
    * @author ShiChao 
    * @return TableDataInfo    返回类型 
    * @throws
     */
    @RequestMapping(value = "/getTravelPrintList/{travelId}", method = RequestMethod.GET)
    public TableDataInfo getTravelPrintList(@PathVariable("travelId") Long travelId){
        List<TravelPrint> list = travelService.getTravelPrintList(travelId);
        return getDataTable(list);
    }
    /**
     * 
    * @Title: getTravelPrintMxList 
    * @Description: 获取报销明细列表信息
    * @param @param travelId
    * @param @return    设定文件 
    * @author ShiChao 
    * @return TableDataInfo    返回类型 
    * @throws
     */
    @RequestMapping(value = "/getTravelPrintMxList/{travelId}", method = RequestMethod.GET)
    public TableDataInfo getTravelPrintMxList(@PathVariable("travelId") Long travelId){
        List<TravelPrint> list = travelService.getTravelPrintMxList(travelId);
        return getDataTable(list);
    }
    /**
     * 
    * @Title: mxExport 
    * @Description: 导出报销明细
    * @param @param travelId
    * @param @param request
    * @param @param response
    * @param @return    设定文件 
    * @author ShiChao 
    * @return AjaxResult    返回类型 
    * @throws
     */
    @GetMapping(value="/mxExport/{travelId}")
    public AjaxResult mxExport(@PathVariable("travelId") Long travelId,HttpServletRequest request, HttpServletResponse response)
    {
        String fileName = "";
    	try {
            fileName = createBxmxFile(travelId,response);
            return AjaxResult.success(fileName);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.success("");
        }
    }
    /**
     * 生成报销明细表
     * @param travelId
     * @param response
     * @return 文件名称
     */
    private String createBxmxFile( Long travelId,HttpServletResponse response) throws Exception{
        String fileName = "";
//        String templateFile = this.getClass().getResource("/").getPath().replaceAll("^\\/", "") + "/templete/xjbxmx.xls";
        String templateFile = "templete/clbxmx.xls";
        Map<String, Object> map = new HashMap<String, Object>() ;
        TravelPrint mainInfo = travelService.getMainTravelPrint(travelId);
        if(mainInfo.getItemName() == null || "".equals(mainInfo.getItemName() )) {
            mainInfo.setItemName("  ");
        }
        if(mainInfo.getItemFinanceNo() == null || "".equals(mainInfo.getItemFinanceNo() )) {
            mainInfo.setItemFinanceNo(" ");
        }
        List<TravelPrint> list = travelService.getTravelPrintMxList(travelId);
        int mxHjdjNum = 0;
        Double mxHjMoney = 0.00;
        for(int i=0;i<list.size();i++) {
        	mxHjdjNum += list.get(i).getInvoiceNum();
            mxHjMoney += list.get(i).getExpenseMoney();
        }
        mainInfo.setMxHjdjNum(mxHjdjNum);
        mainInfo.setMxHjMoney(mxHjMoney);
        if(list != null && list.size()<5){
            int i = 5- list.size();
            for(;i>0;i--){
                list.add(new TravelPrint());
            }
        }
        //解决文件名是中文乱码问题
        //map.put("fileName", "报销明细表") ;
        map.put("mainInfo", mainInfo);
        map.put("clbxmxList", list) ;
        String expenseMonthStr =  getLaseMonthStr(mainInfo.getExpenseTime(),"yyyyMM");
        fileName = mainInfo.getNickName()+"/差旅报销明细表_"+mainInfo.getExpenseName()+expenseMonthStr+".xls";
        FileUtils.createFileByTemplate(fileName,map,templateFile,response);
        return fileName;
    }
    /**
     * 
    * @Title: getLaseMonthStr 
    * @Description: 获取上个月日期，用于文件名
    * @param @param ExpenseTime
    * @param @param formatStr
    * @param @return    设定文件 
    * @author ShiChao 
    * @return String    返回类型 
    * @throws
     */
    private String getLaseMonthStr(Date ExpenseTime,String formatStr) {
    	SimpleDateFormat format = new SimpleDateFormat(formatStr);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(ExpenseTime);
        calendar.set(Calendar.MONTH, calendar.get(Calendar.MONTH) - 1); // 设置为上一个月
        ExpenseTime = calendar.getTime();
        return format.format(ExpenseTime);
    }
}
